package main

import (
	"database/sql"
	"fmt"

	"github.com/go-sql-driver/mysql"
)

var db *sql.DB

func initDB() (err error) {
	cfg := &mysql.Config{
		User:                 "root",
		Passwd:               "root",
		Addr:                 "127.0.0.1:3306",
		DBName:               "go_demo",
		AllowNativePasswords: true,
		ParseTime:            true,
	}
	dsn := cfg.FormatDSN()
	//dsn := "root:root@tcp(127.0.0.1:3306)/go_demo"
	db, err = sql.Open("mysql", dsn) //仅仅校验连接字符串格式是否正确
	if err != nil {
		return
	}

	err = db.Ping() //测试连接
	if err != nil {
		return
	}
	fmt.Println("连接数据库成功！")
	return nil
}

func main() {
	err := initDB()
	fmt.Println(err)

}
